package com.zhentao.payment.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.payment.entity.PaymentOrder;
import com.zhentao.payment.service.PaymentOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付控制器
 * 处理支付相关的请求
 */
@Slf4j
@RestController
@RequestMapping("/api/payment")
public class PaymentController {
    @Autowired
    private PaymentOrderService paymentOrderService;

    /**
     * 创建支付订单
     *
     * @param order 支付订单
     * @return 返回创建的支付订单信息
     */
    @PostMapping("/create")
    public ResponseEntity<?> createOrder(@RequestBody PaymentOrder order) {
        try {
            // 验证支付类型
            if (order.getPaymentType() == null || (order.getPaymentType() != 1 && order.getPaymentType() != 2)) {
                return ResponseEntity.badRequest().body("支付类型无效，必须是1(支付宝)或2(微信)");
            }
            
            PaymentOrder savedOrder = paymentOrderService.createOrder(order);
            return ResponseEntity.ok(savedOrder);
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return ResponseEntity.badRequest().body("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 查询支付订单
     *
     * @param orderNo 订单编号
     * @return 返回支付订单信息
     */
    @GetMapping("/query/{orderNo}")
    public ResponseEntity<?> queryOrder(@PathVariable String orderNo) {
        try {
            PaymentOrder order = paymentOrderService.queryOrder(orderNo);
            return ResponseEntity.ok(order);
        } catch (Exception e) {
            log.error("查询订单失败", e);
            return ResponseEntity.badRequest().body("查询订单失败：" + e.getMessage());
        }
    }

    /**
     * 查询支付订单列表
     *
     * @param orderNo 订单编号
     * @param status 订单状态
     * @param paymentType 支付类型
     * @param page 页码
     * @param size 每页大小
     * @return 返回支付订单列表
     */
    @GetMapping("/query")
    public ResponseEntity<?> queryOrderList(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer paymentType,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size
    ) {
        try {
            IPage<PaymentOrder> result = paymentOrderService.queryOrderList(orderNo, status, paymentType, page, size);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询订单列表失败", e);
            return ResponseEntity.badRequest().body("查询订单列表失败：" + e.getMessage());
        }
    }

    /**
     * 支付订单
     *
     * @param orderNo 订单编号
     * @return 返回支付页面所需的信息
     */
    @PostMapping("/pay/{orderNo}")
    public ResponseEntity<?> pay(@PathVariable String orderNo) {
        try {
            PaymentOrder order = paymentOrderService.queryOrder(orderNo);
            if (order == null) {
                return ResponseEntity.badRequest().body("订单不存在");
            }
            
            // 返回支付页面所需的信息
            Map<String, Object> response = new HashMap<>();
            response.put("orderNo", order.getOrderNo());
            response.put("amount", order.getAmount());
            response.put("qrCodeUrl", "/qrcode/payment.jpg"); // 这里使用您自己的收款码图片路径
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取支付信息失败", e);
            return ResponseEntity.badRequest().body("获取支付信息失败：" + e.getMessage());
        }
    }

    /**
     * 取消支付订单
     *
     * @param orderNo 订单编号
     * @return 处理结果
     */
    @PostMapping("/cancel/{orderNo}")
    public ResponseEntity<?> cancelOrder(@PathVariable String orderNo) {
        try {
            paymentOrderService.cancelOrder(orderNo);
            return ResponseEntity.ok("订单已取消");
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return ResponseEntity.badRequest().body("取消订单失败：" + e.getMessage());
        }
    }

    @GetMapping("/test/qrcode")
    public ResponseEntity<?> testQrCode() {
        try {
            // 返回静态资源路径
            Map<String, String> response = new HashMap<>();
            response.put("qrcodePath", "/qrcode/payment.jpg");
            response.put("message", "请确保图片文件位于 src/main/resources/static/qrcode/payment.jpg");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("测试收款码访问失败", e);
            return ResponseEntity.badRequest().body("测试收款码访问失败：" + e.getMessage());
        }
    }

    @PostMapping("/paid/{orderNo}")
    public ResponseEntity<?> markOrderAsPaid(@PathVariable String orderNo) {
        try {
            paymentOrderService.updateOrderToPaid(orderNo);
            return ResponseEntity.ok("订单已更新为已支付状态");
        } catch (Exception e) {
            log.error("更新订单状态失败", e);
            return ResponseEntity.badRequest().body("更新订单状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近支付订单
     */
    @GetMapping("/recent")
    public ResponseEntity<List<PaymentOrder>> getRecentPayments() {
        LambdaQueryWrapper<PaymentOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(PaymentOrder::getCreateTime)
               .last("LIMIT 10");
        return ResponseEntity.ok(paymentOrderService.list(wrapper));
    }
}
